<template>
	<view>
		<view class="page page-bottom-bar newPrescript">
			<!-- 头部 -->
			<topBar :backUrl="backUrl">
				<!-- <view class="font14 font-0078ff" @click="openName">保存为常用</view>-->
			</topBar>
			<!-- <u-navbar placeholder autoBack leftText="开立处方" rightText="保存为常用" @rightClick="openName"></u-navbar>-->
			<!-- 患者信息 -->
			<view class="part1 box-shadow">
				<view class="font13 font-969696 flex-row-between">
					<view>NO:{{familyInfo.code||''}}</view>
				</view>
				<view class="hospital font15 font-b tc">
					{{userInfo.doctor_info?(userInfo.doctor_info.hospital_name||''):''}}医嘱</view>
				<view class="item flex-row-start">
					<view>患者姓名</view>
					<input class="flex-1" type="text" disabled :value="form.name" @input="Onname"
						placeholder="请输入患者姓名" />
				</view>
				<view class="item flex-row-start">
					<view>患者年龄</view>
					<input class="flex-1" type="text" disabled :value="form.age" @input="Onage" placeholder="请输入患者年龄" />
				</view>
				<view class="item nob flex-row-start">
					<view>患者性别</view>
					<uni-data-checkbox class="sex flex-1" disabled v-model="form.gender" :localdata="gender.range"
						selectedColor="#6bcbb6" selectedTextColor="#1e1e1e" @change="Onsex">
					</uni-data-checkbox>
				</view>
				<!-- 				<view class="item nob flex-row-start">
					<view>处方类型</view>
					<uni-data-checkbox class="sex flex-1"
						v-model="form.recipe_type"
						:localdata="recipe_type.range"
						selectedColor="#6bcbb6"
						selectedTextColor="#1e1e1e"
						@change="Onrecipe_type">
					</uni-data-checkbox>
				</view> 
				<view class="item flex-row-start">
					<view>用药天数</view>
					<input class="flex-1" type="text" :value="form.medication_days" @input="Onmedication_days" placeholder="请输入用药天数" />
				</view>-->
			</view>
			<!-- 诊断信息 -->
			<view class="part2 box-shadow">
				<view class="font14">医嘱</view>
				<textarea :value="form.content" @input="Ontextarea" placeholder="请输入医嘱"
					placeholder-class="placeholderClass"></textarea>
			</view>
			<!-- 药品信息 -->
			<!--<view class="part3 box-shadow">
				<view class="prescript-list drugs-box">
					<view style="font-size: 26rpx;" v-if="businessobj.id">
						药房：{{businessobj.name}}
						<text @click="goNext('/pagesB/business/businessSelect')" style="color: #6bcbb6;padding: 10rpx;margin-left: 10rpx;">更换</text>
					</view>
					<block v-for="(item, index) in drugs" :key="index">
						<view class="item">
							<view class="part2">
								<view class="name font14">{{item.name}} *{{item.number}}</view>
								<view class="font12 font-969696">用法用量：{{item.frequency}}，{{item.consumption}}，{{item.usage}}</view>
							</view>
							<view class="part3 flex-row-end">
								<view class="btn-small grey" @click="del(item.id)">删除</view>
								<view class="btn-small green" @click="goNext('/pagesA/prescript/drugsEdit?mode=edit&id=' + item.id)">编辑用量</view>
							</view>
						</view>
					</block>
				</view>
				<view class="btn font14 tc" v-if="businessobj.id" @click="goNext('/pagesA/prescript/drugsList?business_id='+businessobj.id)">+ 添加药品</view>
				<view class="btn font14 tc" v-else @click="goNext('/pagesB/business/businessSelect')">选择药房</view>
			</view>
		</view>-->
			<!-- 按钮 -->
			<view class="fix-bottom-btn flex-row-center">
				<view class="btn flex-row-center font-ffffff font15" @click="saveadvice">确定</view>
			</view>
		</view>
		<!-- 弹窗-处方名称 -->
		<uni-popup ref="name" type="center">
			<view class="popup-name">
				<view class="font15 tc font-b">处方名称</view>
				<view class="f-input">
					<input class="flex-1" type="text" :value="title" @input="Ontitle" placeholder="请输入处方名称" />
				</view>
				<view class="flex-row-between">
					<view class="btn btn1" @click="closeName">取消</view>
					<view class="btn btn2" @click="save">保存</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Compicker from '@/components/Compicker.vue'
	import topBar from "@/components/ComTopBar.vue";
	export default {
		components: {
			Compicker,
			topBar
		},
		data() {
			return {
				backUrl: '',
				familyId: '', // 就诊人的id
				doctorId: '', // 医生id
				prescriptId: '', // 处方id
				cate: '',
				consultation_id: '',
				familyInfo: {}, // 就诊人信息
				userInfo: {}, // 用户信息
				// 性别
				gender: {
					value: '1',
					range: [{
							value: '1',
							text: "男"
						},
						{
							value: '2',
							text: "女"
						}
					]
				},
				// 处方类型
				recipe_type: {
					value: '1',
					range: [{
							value: '1',
							text: "中药"
						},
						{
							value: '2',
							text: "西药"
						},
						{
							value: '3',
							text: "成药(三医)"
						}
					]
				},
				form: {
					name: '',
					age: '',
					gender: '1',
					recipe_type: '2',
					medication_days: '7',
					content: ''
				},
				title: '', // 处方名称
				drugs: [], // 药品列表

				businessobj: {},
			}
		},
		onLoad(options) {
			this.familyId = options.familyId
			this.doctorId = options.doctorId
			this.prescriptId = options.prescriptId
			this.cate = options.cate
			this.consultation_id = options.consultation_id

			// this.backUrl = '/pagesA/prescript/list?familyId=' + options.familyId + '&doctorId=' + options.doctorId
			this.backUrl = '/pagesA/prescript/list?cate=' + this.cate + '&consultation_id=' + this.consultation_id +
				'&familyId=' + options.familyId + '&doctorId=' + options.doctorId

			// 获取用户信息
			this.$Http({
				url: 'getUserInfo',
				type: 'POST',
				data: {}
			}).then(res => {
				this.userInfo = res.data
			})

			// 就诊人详情
			this.$Http({
				url: 'getUserThePatient',
				data: {
					the_patient_id: this.familyId
				}
			}).then(res => {
				if (res.code == 1) {
					this.familyInfo = res.data
					this.form.name = res.data.name
					this.form.gender = res.data.sex
					this.form.age = this.$base.Onage(res.data.birthday)
				}
			})

			// 处方详情
			if (options.prescriptId) {
				let url = ''
				if (options.type == 'history') {
					url = 'detailsPrescription'
				} else if (options.type == 'public') {
					url = 'detailsPubPrescription'
				} else {
					url = 'detailsCommonlyUsedPrescription'
				}
				this.$Http({
					url: url,
					data: {
						doctor_prescription_id: options.prescriptId
					}
				}).then(res => {
					if (res.code == 1) {
						let arr = []

						if (options.type == 'history') {
							this.form.content = res.data.diagnose
							if (res.data.business_info) {
								if (res.data.business_info) {
									this.$store.commit('selectBusinessobj', res.data.business_info)
									this.businessobj = res.data.business_info
								}
								this.businessobj = res.data.business_info
							}
							res.data.doctor_prescription_access.forEach(item => {
								arr.push({
									id: item.goods_id,
									name: item.goods_name,
									number: item.number,
									usage: item.usages,
									consumption: item.consumptions,
									frequency: item.frequencys,
									remark: item.remark
								})
							})
						} else {
							if (res.data && res.data.goods_list) {
								this.form.content = res.data.diagnosis_proposal
								if (res.data.business_info) {
									this.$store.commit('selectBusinessobj', res.data.business_info)
									this.businessobj = res.data.business_info
								}
								res.data.goods_list.forEach(item => {
									arr.push({
										id: item.goods_id,
										name: item.goods_name,
										number: item.number,
										usage: item.usage,
										consumption: item.consumption,
										frequency: item.frequency,
										remark: item.remark
									})
								})
							}
						}

						this.drugs = arr
						uni.setStorage({
							key: 'drugs',
							data: JSON.stringify(this.drugs)
						});
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			}
		},
		onUnload() {
			this.$store.commit('selectBusinessobj', {})
		},
		onShow() {
			// 从缓存中拿取药品列表信息
			let $drugs = uni.getStorageSync("drugs")
			this.drugs = $drugs ? JSON.parse($drugs) : []

			var businessobj = this.$store.state.businessobj
			if (!this.businessobj.id || !businessobj.id || this.businessobj.id != businessobj.id) {
				this.drugs = []
				uni.removeStorageSync("drugs")
			}
			this.businessobj = businessobj
		},
		methods: {
			Ontitle(e) {
				this.title = e.detail.value
			},
			Onname(e) {
				this.form.name = e.detail.value
			},
			Onage(e) {
				this.form.age = e.detail.value
			},
			Onsex(e) {
				this.form.gender = e.detail.value
			},
			Onrecipe_type(e) {
				this.form.recipe_type = e.detail.value
			},
			Onmedication_days(e) {
				this.form.medication_days = e.detail.value
			},
			Ontextarea(e) {
				this.form.content = e.detail.value
			},
			// 删除药品
			del(id) {
				let that = this
				uni.showModal({
					title: '提示',
					confirmText: '确认',
					confirmColor: '#b8875c',
					cancelText: '取消',
					content: '您确定要删除该药品吗?',
					success: function(res) {
						if (res.confirm) {
							that.drugs.forEach((item, i) => {
								if (item.id == id) {
									that.drugs.splice(i, 1);
									uni.setStorage({
										key: 'drugs',
										data: JSON.stringify(that.drugs)
									});
								}
							})
						}
					}
				});
			},
			// 打开处方名称
			openName() {
				if (this.form.content == '') {
					uni.showToast({
						title: '请输入诊断内容',
						icon: 'none'
					})
					return false
				}
				this.$refs.name.open()
			},
			// 关闭处方名称
			closeName() {
				this.$refs.name.close()
			},
			// 保存为常用处方
			save() {
				if (this.title == '') {
					uni.showToast({
						title: '请输入处方名称',
						icon: 'none'
					})
					return false
				}

				let goods_ids = [],
					usages = [],
					consumptions = [],
					frequencys = [],
					remark = [],
					number = [];
				this.drugs.forEach((item, i) => {
					goods_ids.push(item.id)
					usages.push(item.usage)
					consumptions.push(item.consumption)
					frequencys.push(item.frequency)
					remark.push(item.remark)
					number.push(item.number)
				})
				let obj = {
					business_id: this.businessobj.id || 0,
					name: this.title,
					diagnosis: this.form.content,
					goods_ids: goods_ids.join(','),
					usages: usages.join(','),
					consumptions: consumptions.join(','),
					frequencys: frequencys.join(','),
					remark: remark.join(','),
					number: number.join(',')
				}

				this.$Http({
					url: 'addCommonlyUsedPrescription',
					type: 'POST',
					token: true,
					data: obj
				}).then(res => {
					if (res.code == 1) {
						this.$refs.name.close();
						uni.showToast({
							title: '保存成功'
						})
						uni.removeStorage({
							key: 'drugs'
						});
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			//保存医嘱
			saveadvice() {
				var that = this
				if (this.form.content == '') {
					uni.showToast({
						title: '请输入医嘱内容',
						icon: 'none'
					})
					return false
				}

				// let goods_ids = [],usages = [],consumptions = [],frequencys = [], remark = [], number = [];
				// this.drugs.forEach((item, i) => {
				// 	goods_ids.push(item.id)
				// 	usages.push(item.usage)
				// 	consumptions.push(item.consumption)
				// 	frequencys.push(item.frequency)
				// 	remark.push(item.remark)
				// 	number.push(item.number)
				// })
				var consultation_type = 1
				if (this.cate == 'video') consultation_type = 2
				else if (this.cate == 'report') consultation_type = 3
				let obj = {
					business_id: this.businessobj.id || 0,
					the_patient_id: this.familyId,
					doctor_id: this.doctorId,
					consultation_id: this.consultation_id,
					name: this.form.content,
					consultation_type: consultation_type,
				}
				let pages = getCurrentPages();
				let prevPage = pages[pages.length - 3]; //上一页页面实例
				this.$Http({
					url: 'addAdvice',
					type: 'POST',
					token: true,
					data: obj
				}).then(res => {
					if (res.code == 1) {
						uni.showToast({
							title: '开医嘱成功'
						})
						//uni.removeStorage({ key: 'advice' });
						setTimeout(() => {
							// 回到聊天界面
							// prevPage.$vm.cf_id = res.data.id;
							// prevPage.$vm.diagnose = obj.diagnose;
							// prevPage.$vm.goods_ids = obj.goods_ids;
							uni.navigateBack({
								delta: 2
							});
						}, 2000)

						// console.log('>>>>> createToUser: ', that.$store.FromUser, that.$store.ToUser, that.$store.state)
						// that.$store.dispatch('sendChatMessage',{cate:that.cate, orderno:res.data.orderno, type:'consultationHandle', content:{
						// 	code: "prescript",
						// 	cf_id: res.data.id,
						// }})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			// 发送处方
			send() {
				var that = this
				if (this.form.content == '') {
					uni.showToast({
						title: '请输入诊断内容',
						icon: 'none'
					})
					return false
				}
				if (this.form.medication_days == '') {
					uni.showToast({
						title: '请输入用药天数',
						icon: 'none'
					})
					return false
				}

				let goods_ids = [],
					usages = [],
					consumptions = [],
					frequencys = [],
					remark = [],
					number = [];
				this.drugs.forEach((item, i) => {
					goods_ids.push(item.id)
					usages.push(item.usage)
					consumptions.push(item.consumption)
					frequencys.push(item.frequency)
					remark.push(item.remark)
					number.push(item.number)
				})
				var consultation_type = 1
				if (this.cate == 'video') consultation_type = 2
				else if (this.cate == 'report') consultation_type = 3
				let obj = {
					business_id: this.businessobj.id || 0,
					the_patient_id: this.familyId,
					doctor_id: this.doctorId,
					//recipe_type: this.form.recipe_type,
					recipe_type: 2,
					medication_days: this.form.medication_days,
					diagnose: this.form.content,
					goods_ids: goods_ids.join(','),
					usages: usages.join(','),
					consumptions: consumptions.join(','),
					frequencys: frequencys.join(','),
					remark: remark.join(','),
					number: number.join(','),
					consultation_type: consultation_type,
					consultation_id: this.consultation_id,
				}
				let pages = getCurrentPages();
				let prevPage = pages[pages.length - 3]; //上一页页面实例
				this.$Http({
					url: 'addPrescription',
					type: 'POST',
					token: true,
					data: obj
				}).then(res => {
					if (res.code == 1) {
						uni.showToast({
							title: '开处方成功'
						})
						uni.removeStorage({
							key: 'drugs'
						});
						setTimeout(() => {
							// 回到聊天界面
							prevPage.$vm.cf_id = res.data.id;
							prevPage.$vm.diagnose = obj.diagnose;
							prevPage.$vm.goods_ids = obj.goods_ids;
							uni.navigateBack({
								delta: 2
							});
						}, 2000)

						console.log('>>>>> createToUser: ', that.$store.FromUser, that.$store.ToUser, that.$store
							.state)
						that.$store.dispatch('sendChatMessage', {
							cate: that.cate,
							orderno: res.data.orderno,
							type: 'consultationHandle',
							content: {
								code: "prescript",
								cf_id: res.data.id,
							}
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			// 跳转
			goNext(url) {
				uni.navigateTo({
					url: url
				})
			}
		}
	}
</script>

<style lang="less">
	@import url("style.less");

	/deep/.u-navbar__content__right__text {
		color: #006EFF;
	}
</style>